﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Diagnostics;
using System.IO;
using System.ComponentModel;

namespace AOUtils.Libraries
{
    /// <summary>
    /// Interaction logic for IconDockPanel.xaml
    /// </summary>
    public partial class IconDockPanel : UserControl
    {
        public event EventHandler<EventArgs> Clear;
        public event EventHandler<EventArgs> Add;
        public event EventHandler<ItemChangedEventArgs> SelectedItemChangedHandler;
        private Uri resourceDirectory;
        private BackgroundWorker placer;

        public IconDockPanel()
        {
            InitializeComponent();
            SelectedItemChangedHandler += new EventHandler<ItemChangedEventArgs>(SelectedItemChanged);
            resourceDirectory = new Uri(System.IO.Path.GetFullPath(@".\Resources\"));
            placer = new BackgroundWorker();
        }

        private void SelectedItemChanged(object sender, ItemChangedEventArgs e)
        {
            string path = string.Empty;
            OptimizedItem item = e.Item;
            if (item == null)
            {
                this.Background = null;
                this.ToolTip = null;
                this.SelectedIndex = -1;
            }
            else
            {
                if (File.Exists(path = System.IO.Path.Combine(resourceDirectory.LocalPath, item.Icon.ToString() + ".gif")))
                {
                    this.Background = new ImageBrush(new BitmapImage(new Uri(path)));
                }
                else if (item != null)
                {
                    this.Background = new ImageBrush(new BitmapImage(new Uri(System.IO.Path.Combine(resourceDirectory.LocalPath, "0.gif"))));
                }
                for (int i = 0; i < ContextMenu.Items.Count; i++)
                {
                    MenuItem menuItem = (MenuItem)ContextMenu.Items[i];

                    if (item.Name.Equals(((OptimizedItem)menuItem.Tag).Name))
                    {
                        SelectedIndex = i;
                        break;
                    }
                }
                this.ToolTip = "Ql " + item.Ql.ToString() + " " + item.Name;
            }
        }

        public Slot Slot
        {
            get;
            set;
        }
        private OptimizedItem selectedItem;
        public OptimizedItem SelectedItem
        {
            get
            {
                return selectedItem;
            }
            set
            {
                selectedItem = value;
                OnSelectedItemChanged(new ItemChangedEventArgs(value));
            }
        }
        private int selectedIndex;
        public int SelectedIndex
        {
            get { return selectedIndex; }
            set
            {
                selectedIndex = value;
                if (value != -1 && selectedIndex != value)
                    SelectedItem = (ContextMenu.Items[value] as MenuItem).Tag as OptimizedItem;
            }
        }
        protected virtual void OnSelectedItemChanged(ItemChangedEventArgs args)
        {
            if (SelectedItemChangedHandler != null)
                SelectedItemChangedHandler(this, args);
        }
        protected virtual void OnClear(EventArgs e)
        {
            if(Clear != null)
                Clear(this, e);
        }

        public void ClearItems()
        {
            if (ContextMenu != null)
                this.ContextMenu.Items.Clear();
            SelectedIndex = -1;
            SelectedItem = null;
            ContextMenu = null;
            this.Background = null;
            OnClear(new EventArgs());
        }

        protected virtual void OnAdd(EventArgs e)
        {
            if (Add != null)
                Add(this, e);
        }

        public void AddItem(MenuItem menuItem)
        {
            if (ContextMenu == null)
            {
                this.ContextMenu = new ContextMenu();
                //this.ContextMenu.Items.CanSort;
                
                this.ContextMenu.Items.SortDescriptions.Add(new SortDescription("Tag", ListSortDirection.Descending));
            }
            if (ContextMenu.Items.Count == 0)
            {
                MenuItem mnuItem = new MenuItem();
                mnuItem.Click += new RoutedEventHandler(MenuItemClick);
                this.ContextMenu.Items.Add(mnuItem);
            }
            menuItem.Click += new RoutedEventHandler(MenuItemClick);
            OptimizedItem item = menuItem.Tag as OptimizedItem;
            string path = System.IO.Path.GetFullPath(@".\Resources\" + item.Icon.ToString() + ".gif");
            string nullpath = System.IO.Path.GetFullPath(@".\Resources\0.gif");
            Image image = new Image();
            BitmapImage bmp = null;
            if (File.Exists(path))
                bmp = new BitmapImage(new Uri(path));
            else
                bmp = new BitmapImage(new Uri(nullpath));
            image.Source = bmp;
            image.Height = 16;
            image.Width = 16;
            menuItem.Icon = image;

            //Func<MenuItem, OptimizedItem> selector = mnuItem => mnuItem.Tag as OptimizedItem;

            //int i = 0;
            //List<int> indexes = new List<int>();
            bool add = true;
            for (int x = this.ContextMenu.Items.Count - 1; x >= 0; x--)
            {
                add = true;
                MenuItem mnuItem = this.ContextMenu.Items[x] as MenuItem;
                OptimizedItem oitem = mnuItem.Tag as OptimizedItem;
                if (oitem != null && item.Name.Equals(oitem.Name))
                {
                    if (item.Ql > oitem.Ql || (item.Ql.Equals(oitem.Ql) && item.Id > oitem.Id))
                    {
                        this.ContextMenu.Items.Remove(mnuItem);
                        add = true;
                    }
                    else
                        add = false;
                }
            }
            
            /*foreach (OptimizedItem oitem in this.ContextMenu.Items.Cast<MenuItem>().Select<MenuItem, OptimizedItem>(selector))
            {

                if (item.Name.Equals(oitem.Name))
                {
                    if (item.Ql > oitem.Ql || (item.Ql.Equals(oitem.Ql) && item.Id > oitem.Id))
                    {
                        indexes.Add(i);
                    }
                }
                i++;
                //Console.WriteLine(oitem.Name);
            }
            for (int x = indexes.Count - 1; x >= 0; x--)
                this.ContextMenu.Items.RemoveAt(indexes[x]);*/
            if (add)
                this.ContextMenu.Items.Add(menuItem);
            //this.ContextMenu.Items.Refresh();
            this.ContextMenu.Items.Refresh();
            OnAdd(new EventArgs());
        }

        public void MenuItemClick(object sender, RoutedEventArgs e)
        {
            MenuItem mi = e.Source as MenuItem;
            OptimizedItem item = mi.Tag as OptimizedItem;
            //this.Background = (ImageBrush)mi.Icon;
            SelectedItem = item;
        }

        public bool HasNextItem
        {
            get
            {
                return 
                    ContextMenu != null && 
                    ContextMenu.Items.Count > SelectedIndex + 1 && 
                    ((ContextMenu.Items[SelectedIndex+1] as MenuItem).Tag as OptimizedItem) != null;
            }
        }

        public OptimizedItem NextItem
        {
            get
            {
                return HasNextItem ? (ContextMenu.Items[SelectedIndex+ 1] as MenuItem).Tag as OptimizedItem : null;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedItem != null)
                Process.Start("http://auno.org/ao/db.php?id=" + SelectedItem.Id);
        }
    }
}